'use client'

import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { IconUser, IconMail, IconShield, IconPlus, IconEdit, IconTrash, IconLock, IconArrowLeft, IconRefresh } from "@tabler/icons-react"
import { LIVENESS_BASE_URL } from '@/lib/config'
import useAuthStore from '@/stores/authStore'

interface User {
  id: string
  email: string
  username: string
  role: string
  created_at: string
  has_face: boolean
}

export default function AdminUsersPage() {
  const router = useRouter()
  const [users, setUsers] = useState<User[]>([])
  const [showAddUser, setShowAddUser] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const [isSyncing, setIsSyncing] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState('')
  
  const [newUser, setNewUser] = useState({
    email: '',
    username: '',
    password: '',
    role: 'user'
  })

  // 检查管理员权限
  useEffect(() => {
    const { token, user, isAuthenticated } = useAuthStore.getState()
    
    if (!isAuthenticated()) {
      router.push('/login')
      return
    }
    
    if (!user || user.role !== 'admin') {
      router.push('/dashboard')
      return
    }
    
    loadUsers()
  }, [router])

  const loadUsers = async () => {
    try {
      const endpoint = LIVENESS_BASE_URL
      const response = await fetch(`${endpoint}/v1/admin/users`)
      
      if (response.ok) {
        const result = await response.json()
        setUsers(result.users || [])
      }
    } catch (err) {
      console.error('加载用户列表失败:', err)
    }
  }

  const handleAddUser = async (e: React.FormEvent) => {
    e.preventDefault()
    setIsLoading(true)
    setError('')
    setSuccess('')

    try {
      const endpoint = LIVENESS_BASE_URL
      const response = await fetch(`${endpoint}/v1/auth/register`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(newUser)
      })

      const result = await response.json()

      if (response.ok && result.success) {
        setSuccess('用户创建成功')
        setNewUser({ email: '', username: '', password: '', role: 'user' })
        setShowAddUser(false)
        loadUsers()
      } else {
        setError(result.message || '创建用户失败')
      }
    } catch (err) {
      setError('网络错误，请稍后重试')
    } finally {
      setIsLoading(false)
    }
  }

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target
    setNewUser(prev => ({
      ...prev,
      [name]: value
    }))
  }

  // 同步人脸状态
  const syncFaceStatus = async () => {
    setIsSyncing(true)
    setError('')
    setSuccess('')

    try {
      const endpoint = LIVENESS_BASE_URL
      const response = await fetch(`${endpoint}/v1/face/sync-status`, {
        method: 'POST'
      })

      const result = await response.json()

      if (response.ok && result.success) {
        setSuccess(`状态同步成功！已同步 ${result.synced_count} 个用户的人脸状态`)
        // 同步完成后重新加载用户列表
        setTimeout(() => {
          loadUsers()
        }, 1000)
      } else {
        setError(result.message || '同步失败')
      }
    } catch (err) {
      console.error('同步人脸状态失败:', err)
      setError('网络错误，同步失败')
    } finally {
      setIsSyncing(false)
    }
  }

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 p-4 sm:p-6 lg:p-8">
      <div className="max-w-6xl mx-auto">
        {/* 页面标题 */}
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-6">
          <div className="flex items-center gap-4">
            <Button
              variant="outline"
              onClick={() => router.push('/admin/settings')}
              className="p-2 h-10 w-10 flex-shrink-0"
            >
              <IconArrowLeft className="w-4 h-4" />
            </Button>
            <div>
              <h1 className="text-2xl sm:text-3xl font-bold text-gray-900 dark:text-gray-100">
                用户管理
              </h1>
              <p className="text-sm sm:text-base text-gray-600 dark:text-gray-400 mt-1">
                管理系统用户账号和权限
              </p>
            </div>
          </div>
          <div className="flex gap-3 mt-4 sm:mt-0">
            <Button
              onClick={syncFaceStatus}
              disabled={isSyncing}
              variant="outline"
              className="border-blue-200 text-blue-700 hover:bg-blue-50"
            >
              {isSyncing ? (
                <div className="flex items-center gap-2">
                  <div className="w-4 h-4 border-2 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
                  同步中...
                </div>
              ) : (
                <>
                  <IconRefresh className="w-4 h-4 mr-2" />
                  同步状态
                </>
              )}
            </Button>
            <Button
              onClick={() => setShowAddUser(true)}
              className="bg-blue-600 hover:bg-blue-700 text-white"
            >
              <IconPlus className="w-4 h-4 mr-2" />
              添加用户
            </Button>
          </div>
        </div>

        {/* 错误和成功提示 */}
        {error && (
          <Alert variant="destructive" className="mb-6">
            <AlertDescription>{error}</AlertDescription>
          </Alert>
        )}
        
        {success && (
          <Alert className="mb-6 border-green-200 bg-green-50 dark:bg-green-900/20">
            <AlertDescription className="text-green-700 dark:text-green-300">
              {success}
            </AlertDescription>
          </Alert>
        )}

        {/* 用户列表 */}
        <Card>
          <CardHeader>
            <CardTitle>用户列表</CardTitle>
            <CardDescription>
              当前系统共有 {users.length} 个用户
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="overflow-x-auto rounded-lg border border-gray-200 dark:border-gray-700">
              <table className="w-full table-auto border-collapse">
                <thead className="bg-gray-50 dark:bg-gray-800">
                  <tr className="border-b border-gray-200 dark:border-gray-700">
                    <th className="text-center p-4 font-semibold text-gray-900 dark:text-gray-100">邮箱</th>
                    <th className="text-center p-4 font-semibold text-gray-900 dark:text-gray-100">用户名</th>
                    <th className="text-center p-4 font-semibold text-gray-900 dark:text-gray-100">角色</th>
                    <th className="text-center p-4 font-semibold text-gray-900 dark:text-gray-100">人脸状态</th>
                    <th className="text-center p-4 font-semibold text-gray-900 dark:text-gray-100">创建时间</th>
                  </tr>
                </thead>
                <tbody>
                  {users.map((user) => (
                    <tr key={user.id} className="border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors">
                      <td className="p-4 text-center text-gray-900 dark:text-gray-100">{user.email}</td>
                      <td className="p-4 text-center text-gray-900 dark:text-gray-100">{user.username}</td>
                      <td className="p-4 text-center">
                        <div className="flex justify-center">
                          <span className={`inline-flex items-center px-3 py-1 rounded-full text-xs font-medium ${
                            user.role === 'admin' 
                              ? 'bg-purple-100 text-purple-800 dark:bg-purple-900/20 dark:text-purple-300'
                              : 'bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-300'
                          }`}>
                            <IconShield className="w-3 h-3 mr-1" />
                            {user.role === 'admin' ? '管理员' : '普通用户'}
                          </span>
                        </div>
                      </td>
                      <td className="p-4 text-center">
                        <div className="flex justify-center">
                          <span className={`inline-flex items-center px-3 py-1 rounded-full text-xs font-medium ${
                            user.has_face 
                              ? 'bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-300'
                              : 'bg-gray-100 text-gray-800 dark:bg-gray-900/20 dark:text-gray-300'
                          }`}>
                            {user.has_face ? '已录入' : '未录入'}
                          </span>
                        </div>
                      </td>
                      <td className="p-4 text-center text-gray-600 dark:text-gray-400">
                        {new Date(user.created_at).toLocaleDateString()}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
              
              {users.length === 0 && (
                <div className="text-center py-8 text-gray-500 dark:text-gray-400">
                  暂无用户数据
                </div>
              )}
            </div>
          </CardContent>
        </Card>

        {/* 添加用户模态框 */}
        {showAddUser && (
          <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
            <Card className="w-full max-w-md">
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <IconUser className="w-5 h-5" />
                  添加新用户
                </CardTitle>
                <CardDescription>
                  创建新的系统用户账号
                </CardDescription>
              </CardHeader>
              <CardContent>
                <form onSubmit={handleAddUser} className="space-y-4">
                  {/* 邮箱 */}
                  <div className="space-y-2">
                    <Label htmlFor="email">邮箱地址</Label>
                    <div className="relative">
                      <IconMail className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
                      <Input
                        id="email"
                        name="email"
                        type="email"
                        value={newUser.email}
                        onChange={handleInputChange}
                        placeholder="请输入邮箱地址"
                        className="pl-10"
                        required
                      />
                    </div>
                  </div>

                  {/* 用户名 */}
                  <div className="space-y-2">
                    <Label htmlFor="username">用户名</Label>
                    <div className="relative">
                      <IconUser className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
                      <Input
                        id="username"
                        name="username"
                        type="text"
                        value={newUser.username}
                        onChange={handleInputChange}
                        placeholder="请输入用户名"
                        className="pl-10"
                        required
                      />
                    </div>
                  </div>

                  {/* 密码 */}
                  <div className="space-y-2">
                    <Label htmlFor="password">初始密码</Label>
                    <div className="relative">
                      <IconLock className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
                      <Input
                        id="password"
                        name="password"
                        type="password"
                        value={newUser.password}
                        onChange={handleInputChange}
                        placeholder="请输入初始密码"
                        className="pl-10"
                        required
                      />
                    </div>
                  </div>

                  {/* 角色 */}
                  <div className="space-y-2">
                    <Label htmlFor="role">用户角色</Label>
                    <div className="relative">
                      <IconShield className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
                      <select
                        id="role"
                        name="role"
                        value={newUser.role}
                        onChange={handleInputChange}
                        className="w-full pl-10 pr-3 py-2 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                      >
                        <option value="user">普通用户</option>
                        <option value="admin">管理员</option>
                      </select>
                    </div>
                  </div>

                  {/* 按钮 */}
                  <div className="flex gap-3 pt-4">
                    <Button
                      type="button"
                      variant="outline"
                      onClick={() => setShowAddUser(false)}
                      className="flex-1"
                      disabled={isLoading}
                    >
                      取消
                    </Button>
                    <Button
                      type="submit"
                      className="flex-1 bg-blue-600 hover:bg-blue-700 text-white"
                      disabled={isLoading}
                    >
                      {isLoading ? '创建中...' : '创建用户'}
                    </Button>
                  </div>
                </form>
              </CardContent>
            </Card>
          </div>
        )}
      </div>
    </div>
  )
}

